package com.sale.succ.forms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import com.sale.succ.components.DateSelectPanel;
import com.sale.succ.components.DefForm;
import com.sale.succ.components.DefVerScrollPanel;
import com.sale.succ.objects.Session;
import com.sale.succ.system.TradeMarketException;
import com.sale.succ.system.txt.ObjectsProvider;
import com.sale.succ.utils.DateFormatter;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.fx.gui.WindowConstants;
import eve.sys.Event;
import eve.sys.EventListener;
import eve.ui.CellPanel;
import eve.ui.CheckBox;
import eve.ui.Choice;
import eve.ui.ComboBox;
import eve.ui.ControlConstants;
import eve.ui.Gui;
import eve.ui.Input;
import eve.ui.Label;
import eve.ui.event.ControlEvent;

public class ClientPropertiesForm extends DefForm {
	private CheckBox certificates;
	private CheckBox asFact;
	private CheckBox moneyCondition;
	private CheckBox tablet;
	private CheckBox exchange;
	private ComboBox formOrder;

	private ComboBox dateGive;
	private DateSelectPanel payDate;

	private CheckBox notesCheck;
	private Input notes;

	boolean enableCertificates = Session.getInstance().isCertificates();
	boolean enableAsFact = Session.getInstance().isAsFact();
	boolean enableMoneyCondition = Session.getInstance().isMoneyCondition();
	boolean enableTablet = Session.getInstance().isTablet();
	boolean enableExchange = Session.getInstance().isExchange();
	boolean enableNotes = false;
	
	public ClientPropertiesForm() {
		title = TraderHelper.getLabel(TraderConstants.PARAM_OF_ORDER);

		CellPanel main = new CellPanel();
		main.addNext(
				new Label(TraderHelper.getLabel(TraderConstants.FORM_ORDER)))
				.setCell(VSHRINK).setControl(LEFT);
		main.addLast(getFormOrder()).setCell(VSHRINK).setControl(LEFT);
		main.addNext(new Label(TraderHelper.getLabel(TraderConstants.NOTES)))
				.setCell(VSHRINK).setControl(LEFT);
		main.addLast(getDateGive()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getCertificates()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getAsFact()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(new Label(TraderHelper.getLabel(TraderConstants.TERMS)))
				.setCell(VSHRINK).setControl(LEFT);
		main.addNext(new Label(TraderHelper.getLabel(TraderConstants.PAY_DATE))
				.setCell(VSHRINK).setControl(LEFT));
		main.addLast(getPayDate()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getMoneyCondition()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getTablet()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getExchange()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getNotesCheck()).setCell(VSHRINK).setControl(LEFT);
		main.addLast(getNotes()).setCell(VSHRINK).setControl(LEFT);

		DefVerScrollPanel mainScroll = new DefVerScrollPanel(main);

		addLast(mainScroll);

		doButtons(CANCELB | OKB);
		windowFlagsToSet |= WindowConstants.FLAG_MAXIMIZE;
		ok.addListener(new EventListener() {
			public void onEvent(Event ev) {
				if (ev.type == ControlEvent.PRESSED) {
					if (saveProperties()) {
						new TradeForm().execute();
					}
				}
			}

		});
	}

	private boolean saveProperties() {
		Session.getInstance().setAsFact(getAsFact().getState());
		Session.getInstance().setCertificates(getCertificates().getState());
		Session.getInstance().setExchange(getExchange().getState());
		Session.getInstance().setMoneyCondition(getMoneyCondition().getState());
		Session.getInstance().setTablet(getTablet().getState());
		String fwName = getFormOrder().input.text;
		
		Session.getInstance().setFw(namesToId.get(fwName).toString());
		
		Date payDate = getPayDate().getDate();
		Date giveDate = DateFormatter.stringToDate(getDateGive().input.text);

		Calendar payCal = Calendar.getInstance();
		payCal.setTime(payDate);
		makeZeroCal(payCal);

		Calendar now = Calendar.getInstance();
		makeZeroCal(now);
		if ((payCal.getTimeInMillis() - now.getTimeInMillis()) > (new Long(
				30 * 24 * 60 * 60) * 1000)) {
			new TradeMarketException(TraderHelper
					.getLabel(TraderConstants.WRONG_PAY_DATE));
			return false;
		}
		if ((payCal.getTimeInMillis() - now.getTimeInMillis()) < 0) {
			new TradeMarketException(TraderHelper
					.getLabel(TraderConstants.WRONG_DATE)
					+ ":"
					+ TraderHelper.getLabel(TraderConstants.PAY_LABEL_DATE));
			return false;
		}

		Session.getInstance().setPayDate(payDate);
		Session.getInstance().setGiveDate(giveDate);
		Session.getInstance().setNotes(getNotes().text);

		return true;
	}

	private void makeZeroCal(Calendar cal) {
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
	}

	public CheckBox getCertificates() {
		if (certificates == null) {
			certificates = new CheckBox(TraderHelper
					.getLabel(TraderConstants.CERTIFICATES));
			certificates.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						enableCertificates = !enableCertificates;
					}
				}
			});
		}

		return certificates;
	}

	public CheckBox getAsFact() {
		if (asFact == null) {
			asFact = new CheckBox(TraderHelper.getLabel(TraderConstants.ASFACT));
			asFact.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						enableAsFact = !enableAsFact;
						enableMoneyCondition = !enableMoneyCondition;
						if (getMoneyCondition().getState()) {
							getMoneyCondition().setState(false);
						}
						getMoneyCondition().set(ControlConstants.NotEditable,
								!enableAsFact);
						getMoneyCondition().repaint();

						if (enableAsFact) {
							setPayDateEqualsGiveDate();
						}

						getPayDate().setEnabled(!enableAsFact);

					}
				}
			});
		}
		return asFact;
	}

	public CheckBox getMoneyCondition() {
		if (moneyCondition == null) {
			moneyCondition = new CheckBox(TraderHelper
					.getLabel(TraderConstants.MONEY_COND));
			moneyCondition.set(ControlConstants.NotEditable,

			!enableAsFact);

			moneyCondition.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						enableMoneyCondition = !enableMoneyCondition;
					}
				}
			});
		}
		return moneyCondition;
	}

	public CheckBox getTablet() {
		if (tablet == null) {
			tablet = new CheckBox(TraderHelper.getLabel(TraderConstants.TABLET));
			tablet.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						enableTablet = !enableTablet;
					}
				}
			});
		}
		return tablet;
	}

	public CheckBox getExchange() {
		if (exchange == null) {
			exchange = new CheckBox(TraderHelper
					.getLabel(TraderConstants.EXCHANGE));
			exchange.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						enableExchange = !enableExchange;
					}
				}
			});
		}
		return exchange;
	}

	private Input getNotes() {
		if (notes == null) {
			notes = new Input();
			notes.set(ControlConstants.NotEditable, !enableNotes);
			notes.setPreferredSize(Gui.getScreenSize().width - 5, 20);
		}
		return notes;
	}

	private CheckBox getNotesCheck() {
		if (notesCheck == null) {
			notesCheck = new CheckBox(TraderHelper.getLabel(TraderConstants.NOTES_1));
			notesCheck.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						enableNotes = !enableNotes;
						getNotes().set(ControlConstants.NotEditable,
								!enableNotes);
						getNotes().repaint();
					}
				}
			});
		}
		return notesCheck;
	}

	private DateSelectPanel getPayDate() {
		if (payDate == null) {
			payDate = new DateSelectPanel(TraderHelper
					.getLabel(TraderConstants.PAY_LABEL_DATE));

		}
		return payDate;
	}

	public ComboBox getFormOrder() {
		if (formOrder == null) {
			formOrder = new ComboBox(getFormOrderChoice());
			formOrder.input.set(ControlConstants.NotEditable, true);
			formOrder.select(0);
			formOrder.setPreferredSize(150, 20);
		}
		return formOrder;
	}

	public ComboBox getDateGive() {
		if (dateGive == null) {
			dateGive = new ComboBox(getDateGiveChoice());
			dateGive.input.set(ControlConstants.NotEditable, true);
			dateGive.select(0);
			dateGive.setPreferredSize(100, 20);
			dateGive.actionOnChoiceSelect = true;
			dateGive.addListener(new EventListener() {
				public void onEvent(Event ev) {
					if (ev.type == ControlEvent.PRESSED) {
						if (enableAsFact) {
							setPayDateEqualsGiveDate();
						}

					}
				}
			});
		}
		return dateGive;
	}

	private void setPayDateEqualsGiveDate() {
		getPayDate().setDate(getDateGive().input.text);
	}

	private Choice dateGiveChoice;
	private Choice formOrderChoice;

	private Choice getDateGiveChoice() {
		if (dateGiveChoice == null) {
			dateGiveChoice = new Choice(getDates(), 0);
		}
		return dateGiveChoice;
	}

	private Choice getFormOrderChoice() {
		if (formOrderChoice == null) {
			formOrderChoice = new Choice(getFormOrdersData(), 0);
		}
		return formOrderChoice;
	}
	private ArrayList privateNames;
	private HashMap namesToId = new HashMap();
	private ArrayList getPrivateNames(){
		if(privateNames == null){
			privateNames = new ArrayList();			
			Collection names = ObjectsProvider.getInstance().getPrivateCollection().keySet();
			Iterator it = names.iterator();
			while(it.hasNext()){
				Object key = it.next();
				String name = ObjectsProvider.getInstance().getPrivateCollection().get(key).toString();
				namesToId.put(name, key);
				privateNames.add(name);
			}
			
		}
		return privateNames;
	}
	
	private String[] chpNames;
	
	private String[] getFormOrdersData() {
		if(chpNames==null){
			chpNames = new String[getPrivateNames().size()];
			for(int i=0;i<getPrivateNames().size();i++){
				chpNames[i]=getPrivateNames().get(i).toString();
			}
		}
		return chpNames;
	}

	private String[] getDates() {
		Calendar calNow = Calendar.getInstance();
		String[] dates = new String[7];

		for (int i = 0; i < dates.length; ++i) {
			dates[i] = DateFormatter.dateToString(calNow.getTime(), ".");
			Date tommorow = calNow.getTime();
			tommorow.setTime(tommorow.getTime() + 60 * 60 * 24 * 1000);
			calNow.setTime(tommorow);
		}
		return dates;
	}

	public boolean handleAction(String action) {
		return super.handleAction(action);
	}

	public boolean canExit(int exitCode) {
		if (exitCode == 1)
			return false;
		return super.canExit(exitCode);
	}
}
